package org.mashibing.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.mashibing.dto.TokenResult;


/**
 * @author:
 * @create: 2024/3/28 9:21
 * @description: JWT工具类
 */
public class JwtUtils {

    /**
     * 盐
     */
    private static final String SIGN = "djh";

    private static final String JWT_KEY_PHONE = "phone";
    private static final String JWT_KEY_IDENTITY = "identity";
    private static final String TOKEN_TYPE = "tokenType";
    private static final String TOKEN_TIME = "tokenTime";

    /**
     * 生成token
     */
    public static String generatorToken(String phone, String identity, String tokenType) {
        JWTCreator.Builder builder = JWT.create();
        // 赋值
        builder.withClaim(JWT_KEY_PHONE, phone);
        builder.withClaim(JWT_KEY_IDENTITY, identity);
        builder.withClaim(TOKEN_TIME, System.currentTimeMillis());
        builder.withClaim(TOKEN_TYPE, tokenType);
        // 生成token
        return builder.sign(Algorithm.HMAC256(SIGN));
    }

    /**
     * 解析token
     */
    public static TokenResult pareToken(String token) {
        DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
        String phone = verify.getClaim(JWT_KEY_PHONE).asString();
        String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();

        return new TokenResult(phone, identity);
    }


}
